/**
 * @author Caius
 * @description
 *      自定义redis序列化方式,避免使用默认的jdk序列化方式
 *      jdk序列化问题:
 *          1.阅读体验差
 *          2.序列化之后容器的体积比较大，占用过多内存
 * @version 1.0
 * @since Created in 2025-01-02
 */

package com.itsense.stock.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.concurrent.TimeUnit;

@Configuration
public class CacheConfig {
    /**
     * 自定义模版类,要保证bean的名称必须叫redisTemplate,否则场景依赖会自动装配,导致相同类型的bean出现多个
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate redisTemplate(@Autowired RedisConnectionFactory factory){
        //1.构建redisTemplate的模版
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 构建缓存bean
     * @return
     */
    @Bean
    public Cache<String, Object> caffeineCache(){
        Cache<String, Object> cache = Caffeine
                .newBuilder()
                .maximumSize(200) //缓存最大数量上限
//                .expireAfterAccess(1, TimeUnit.SECONDS) //访问一秒之后删除
//                .expireAfterWrite(1,TimeUnit.SECONDS) //写入一秒之后删除
                .initialCapacity(100) //初始的缓存空间大小
                .recordStats() //开启统计
                .build();
        return cache;
    }

}
